<?php
declare (strict_types = 1);

namespace app\mall\controller;


use app\BaseController;
use app\common\model\Message;
use think\facade\Db;

class ImController extends BaseController
{
    /**
     * 登录
     */
    public function login()
    {

    }

    /**
     * 登出
     */
    public function logout()
    {

    }

    public function upload()
    {
        $type = '';
        $data['src'] = '';//文件url
        if ($type = 'file') {
            $data['name'] = '';//文件名
        }
    }

    /**
     * 获取好友
     */
    public function getFriends()
    {
        $user_id = $this->auth()->id();
        $list = Db::name('users')
            ->alias('u')
            ->leftJoin('user_friends uf', 'u.id=uf.friend_user_id and uf.user_id=1')
            ->field('u.id,username,avatar,city')
            ->where('u.id', '<>', $user_id)
            ->where('uf.friend_user_id', 'NULL')
            ->paginate([
                'list_rows' => 12,
                'var_page' => 'page',
            ]);

        return $this->result(0, '', $list->items(), ['pages' => $list->lastPage()]);
    }

    /**
     * 添加好友
     */
    public function applyFriend()
    {
        $param = $this->request->param();
        $user_id = $this->auth()->id();
        $from = $param['from'];

        // 查询有无申请
        $result = Db::name('messages')
            ->where('user_id', $user_id)
            ->where('from', $from)
            ->find();
        if ($result) {
            return $this->success('添加成功');
        }

        $data = [
            "uid" => $user_id,
            "content" => "申请添加你为好友",
            "from" => $from,
            "from_group" => $param['from_group'],
            "remark" => $param['remark'],
            "type" => 1,
            "created_at" => date('Y-m-d H:i:s'),
            "updated_at" => date('Y-m-d H:i:s'),
        ];
        $result = Db::name('messages')->save($data);
        if ($result) {
            return $this->success('添加成功');
        }
        return $this->error('添加失败');
    }

    /**
     * 同意好友
     * @return \think\Response
     */
    public function agreeFriend()
    {
        $post = $this->request->post();
        $uid = $this->auth()->id();

        $message = Message::where('from', $post['uid'])
            ->where('uid', $uid)
            ->find();

        $data = [
            [
                'group_name_id' => $post['group'],
                'user_id' => $uid,
                'friend_user_id' => $post['uid']
            ],
            [
                'group_name_id' => $message->from_group,
                'user_id' => $post['uid'],
                'friend_user_id' => $uid
            ]
        ];
        Db::name('user_friends')->insertAll($data);

        $message->from = 0;
        $message->from_group = 0;
        $message->content = $this->auth()->user()->username . ' 同意了你的好友申请';
        $result = $message->save();

        if ($result) {
            return $this->success('添加成功');
        }
        return $this->error('添加失败');
    }

    /**
     * 拒绝好友
     * @return \think\Response
     */
    public function refuseFriend()
    {
        $message = Message::with('user')
            ->where('from', $this->request->post('uid'))
            ->where('uid', $this->auth()->id())
            ->find();
        $message->from = 0;
        $message->from_group = 0;
        $message->content = $message->user->username . ' 拒绝了你的好友申请';
        $result = $message->save();
        if ($result) {
            return $this->success('添加成功');
        }
        return $this->error('添加失败');
    }

    public function removeFriend()
    {

    }

    public function getGroups()
    {
        Db::name('users')->page(1, 10)->select();
    }

    /**
     * 添加群
     */
    public function applyGroup()
    {

    }

    /**
     * 获取消息列表
     */
    public function getMessages()
    {
        $read = $this->request->get('read');
        if ($read) {
            $where[] = ['read', '=', $read];
        }

        $uid = $this->auth()->id();
        $where[] = ['user_id', '=', $uid];

        $map[] = ['uid', '=', $uid];
        $map[] = ['from', '>', 0];

        $list = Message::with(['user' => function ($query) {
            $query->field('id,username,avatar,sign');
        }])
            ->where(function ($query) use ($where) {
                $query->where($where);
            })->whereOr(function ($query) use ($map) {
                $query->where($map);
            })
            ->field('id,content,uid,from,from_group,type,remark,href,read,created_at as time')
            ->order('id desc')
            ->select();
        return $this->success('添加成功', $list);
    }

    /**
     * 发送消息
     * @param string $uid
     * @param string $content
     * @return bool
     */
    public function sendMessage($uid = 1, $content = 'hello')
    {
        $fp = stream_socket_client("tcp://bengbu.link:2346", $errno, $errstr, 30);
        if (!$fp) {
            return false;
        } else {
            $data = ['type'=>'message', 'data'=> ['id' => $uid, 'content' => $content]];
            fwrite($fp, json_encode($data) . "\n");
            $result = fread($fp, 8192);
            fclose($fp);

            print_r($result);
            return $result == 'success';
        }
    }

    /**
     * 撤回消息
     */
    public function revokeMessage()
    {

    }

    /**
     * 设置消息已读
     */
    public function readMessage()
    {
        $result = Message::where('read', 0)
            ->where('type', 1)
            ->update(['read' => 1, 'uid' => $this->auth()->id()]);
        if ($result) {
            return $this->success('操作成功');
        }
        return $this->error('操作失败');
    }

    /**
     * 获取好友列表
     */
    public function getList()
    {
        $user_id = $this->auth()->id();
        $mine = Db::name('users')->field('id,username,avatar,sign')->find($user_id);
        $mine['status'] = 'online';
        $mine['count'] = 0;// 未读消息

        $friend = Db::name('user_friends')
            ->alias('uf')
            ->leftJoin('users u', 'uf.friend_user_id=u.id')
            ->leftJoin('user_group_names ugn', 'ugn.id=uf.group_name_id')
            ->where('uf.user_id', '=', $user_id)
            ->field('ugn.id as groupid,ugn.name as groupname,u.id,u.username,u.avatar,u.sign,u.status')
            ->select();

        $data = [];
        foreach ($friend as $item) {
            $id = $item['groupid'];
            $data[$id]["id"] = $id;
            $data[$id]["groupname"] = $item['groupname'];
            $item['status'] = $item['status'] ? 'online' : 'offline';
            unset($item['groupid']);
            unset($item['groupname']);
            $data[$id]['list'][] = $item;
        }
        $friend = $data;

        $group = Db::name('user_groups')
            ->field('id,name as groupname,avatar')
            ->where('user_id', '=', $user_id)->select();

        $data = [
            'mine' => $mine,
            'friend' => $friend,
            'group' => $group
        ];
        return $this->result(0, '', $data);
    }

    /**
     * 获取群组成员
     * @param $id
     */
    public function getMembers($id)
    {
        $data = Db::name('user_group_members')
            ->alias('ugm')
            ->leftJoin('users u', 'ugm.user_id=u.id')
            ->field('u.id,u.username,u.avatar,u.sign')
            ->where('group_id', '=', $id)->select();
        return $this->result(0, '', ['list' => $data]);
    }

    /**
     * 修改签名
     **/
    public function setSign()
    {
        $sign = $this->request->param('sign');
        Db::name('users')->where('id', '')->update(['sign' => $sign]);
        $data = [
            'code' => 0,
            'msg' => "",
            'data' => ''
        ];
        return '修改成功';
    }

    /**
     * 修改系统皮肤
     */
    public function setSkin()
    {
        //记录皮肤
        $signature = $this->request->param('sign');
        //实际使用请严格按照该格式返回
        $data = [
            'code' => 0,
            'msg' => "",
            'data' => [
                //路径
                'src' => '',
            ],
        ];
        return json($data);
    }

    /**
     * 修改在线状态
     */
    public function setOnline()
    {
        $status = $this->request->param('status');
        $userId = '';
        $status = $status == 'online' ? 1 : 0;
        Db::name('users')->where('user_id', $userId)->update(['status' => $status]);
        $data = [
            'code' => 0,
            'msg' => '操作成功',
            'data' => $status ? '上线' : '下线'
        ];
        return json($data);
    }
}